import os


def count_line_num(flie_path, single_line_annotation='#', multi_line_annotation_start=('"""', "'''"),
                   multi_line_annotation_end=('"""', "'''",)):
    """
    统计单个文件代码行数
    :param flie: 代码文件地址
    :param single_line_annotation: 单行注释标识，如python代码'#'
    :param multi_line_annotation_start: 多行注释开始标识，如python代码 '''
    :param multi_line_annotation_end: 多行注释结束标识，如python代码 '''
    :return: 代码行数，空行行数，注释行数
    """
    code_num = 0  # 代码行数
    blank_num = 0  # 空行行数
    annotation_num = 0  # 注释行数
    with open(flie_path, encoding='utf8') as f:
        flag = False  # 多行注释表示位， True表示多行注释  False表示代码
        for i in f.readlines():
            i = i.strip().strip('\n')
            if not i:  # 判断是否为空行
                # print('空行' + i)
                blank_num += 1
                continue
            else:
                if i.startswith(single_line_annotation):  # 单行注释
                    annotation_num += 1
                    # print('注释 ' + i)
                    continue
                if i.startswith(multi_line_annotation_start) and i.endswith(multi_line_annotation_end):  # 多行注释标识注释单行
                    annotation_num += 1
                    # print('注释 ' + i)
                    continue
                if not flag and i.startswith(multi_line_annotation_start):  # 多行注释开始
                    flag = True
                    annotation_num += 1
                    # print('注释 ' + i)
                    continue
                if flag:  # 多行注释
                    # print('注释 ' + i)
                    annotation_num += 1
                    if i.endswith(multi_line_annotation_end):  # 多行注释结束
                        flag = False
                    continue
                # print('代码' + i)
                code_num += 1
    return code_num, blank_num, annotation_num


def sum_code(file_dir):
    file_list = []  # 定义文件列表
    for root, dirs, files in os.walk(file_dir):  # 读取目录下的所有文件
        t = [os.path.join(root, i) for i in files]
        file_list += t
    total_code_num = 0
    total_blank_num = 0
    total_annotation_num = 0
    for i in file_list:
        code_num, blank_num, annotation_num = 0, 0, 0
        if i.endswith('.py'):  # python文件
            code_num, blank_num, annotation_num = count_line_num(i)
        # if i.endswith('.html'):  # html文件
        #     code_num, blank_num, annotation_num = count_line_num(i, single_line_annotation='//',
        #                                                          multi_line_annotation_start=('/*', '<!--', '{#'),
        #                                                          multi_line_annotation_end=('*/', '-->', '#}'))
        total_code_num += code_num
        total_blank_num += blank_num
        total_annotation_num += annotation_num
    return total_code_num